package com.bb.blog.security.config;

import com.bb.blog.security.common.CommonAccessDeniedHandler;
import com.bb.blog.security.common.CommonAuthenticationEntyPoint;
import com.bb.blog.security.filter.TokenFilter;
import com.bb.blog.web.constant.CommonServerExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
import org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter;


@Order(1)
@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Qualifier("userDetailsServiceImpl")
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    @Lazy
    TokenStore tokenStore;


    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        ProviderManager authenticationManager = (ProviderManager)super.authenticationManager();
        authenticationManager.getProviders().add(new AuthenticationProvider() {
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                UsernamePasswordAuthenticationToken t = (UsernamePasswordAuthenticationToken) authentication.getPrincipal();
                return t;
            }

            @Override
            public boolean supports(Class<?> authentication) {
                return authentication.equals(PreAuthenticatedAuthenticationToken.class);
            }
        });

        return super.authenticationManager();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .exceptionHandling()
            .authenticationEntryPoint(new CommonAuthenticationEntyPoint())
            .accessDeniedHandler(new CommonAccessDeniedHandler())
            .and()
            .csrf().disable()

            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .addFilterAfter(new TokenFilter(tokenStore), DefaultLoginPageGeneratingFilter.class)
            .authorizeRequests().antMatchers("/oauth/user").authenticated()
            .anyRequest().permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder());
    }

    /**
     * ================  Spring Bean ================
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }


}
